package com.ken.apkmanager3;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/apks")
public class ApkSeriesController {
    private static final Log log = LogFactory.getLog(ApkSeriesController.class);

    @GetMapping
    public List<ApkInfoBean> apkInfo() {
        if (log.isTraceEnabled()) {
            log.trace("接收----");
        }
        List<ApkInfoBean> beanList = new ArrayList<>();
        beanList.add(new ApkInfoBean("测试APP", "com.ken.testapp", "1.0.1", 1));
        beanList.add(new ApkInfoBean("测试APP", "com.ken.testapp", "1.0.2", 2));

        return beanList;
    }


    @PostMapping(value = "/{id}/photos", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void addPhoto(@PathVariable int id, @RequestParam("photo") MultipartFile imgFile) throws Exception {
        if (log.isTraceEnabled()) {
            log.trace("接收文件" + id + "收到文件" + imgFile.getOriginalFilename());
        }

//        保存文件
        FileOutputStream fos = new FileOutputStream("target/" + imgFile.getOriginalFilename());
        IOUtils.copy(imgFile.getInputStream(), fos);
        fos.close();
    }

    @GetMapping(value = "{id}/icon", produces = MediaType.IMAGE_JPEG_VALUE, params = MediaType.IMAGE_PNG_VALUE)
    public byte[] getIcon(@PathVariable int id) throws Exception {
        if (log.isTraceEnabled()) {
            log.trace("getIcon" + id);
        }

        String iconFile = "src/test/resources/111.jpeg";
        InputStream is = new FileInputStream(iconFile);
        return IOUtils.toByteArray(is);
    }

}
